package api

import (
	"encoding/base64"
	"fmt"
	"longmen/server/config/global"
	"longmen/server/internal/services/consumers/publisher"
	"longmen/server/pkg/common/api_models"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/encrypt"
	string2 "longmen/server/pkg/common/helper/string"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/common/sdk/tx"
	"longmen/server/pkg/db/mysql/models/models_main"
	cache2 "longmen/server/pkg/db/redis/cache"
	"strings"
	"time"

	"github.com/labstack/echo/v4"
)

// @Summary 配置參數
// @Description 配置參數
// @Accept  json
// @Produce  json
// @Tags Config
// @Param reg-source header string true "渠道号"
// @Param device-info header string true "设备号"
// @Success 200 {object} api_models.GetCommonConfigResp "result"
// @Router /api/config/getCommonConfig [POST]
func (base *Controller) GetCommonConfig(c echo.Context) error {

	regSource := base.GetRegSource(c)
	configPri := cache2.GetConfigPri()
	var configPub *models_main.ConfigPub
	// if cache2.IsSemFromDownload(device) {

	device := base.GetDeviceInfo(c)
	switch {
	case regSource != "" && cache2.IsConfigSource(regSource):
		//单独渠道配置
		configPub = cache2.GetConfigSource(device, regSource)
	case regSource != "" && cache2.IsJoycircle(regSource):
		//悦动圈渠道包
		configPub = cache2.GetConfigPubJoycircle(device, regSource)
	case regSource != "" && cache2.IsSpec(regSource):
		//特殊渠道包
		configPub = cache2.GetConfigPubSpec(device, regSource)
	case regSource != "" && cache2.IsSem(regSource):
		site := base.GetSite(c)
		// 渠道包判断
		if site == "zb2" { // 绿包web
			configPub = cache2.GetConfigPubSemWeb()
		} else {
			configPub = cache2.GetConfigPubSem(device, regSource)
		}
	default:
		configPub = cache2.GetConfigPub()
	}

	streams := make([]map[string]interface{}, 0)
	_ = util.Json2Struct(configPub.StreamUrl, &streams)

	ticketSwitch := cache2.GetConfigPubByTicketSwitch()
	global.Log.Warnf("echo_configPub: %+v", configPub)
	//if err != nil {
	//	return common.BuildFail(c, 1, "", err)
	//}
	config := &api_models.GetCommonConfigResp{
		QcloudAppid:             configPri.QcloudAppid,
		CosBucket:               configPri.CosBucket,
		CosRegion:               configPri.CosRegion,
		CosFolderImage:          configPri.CosFolderImage,
		CosFolderBlurimage:      configPri.CosFolderBlurimage,
		ImSdkappid:              configPri.ImSdkappid,
		WxAppid:                 configPri.WxAppid,
		UniversalLink:           configPri.UniversalLink,
		QqAppid:                 configPri.QqAppid,
		QqAppkey:                configPri.QqAppkey,
		ExchangeRate:            configPri.ExchangeRate,
		WithdrawMin:             configPri.WithdrawMin,
		BeautyChannel:           configPri.BeautyChannel,
		TisdkKey:                configPri.TisdkKey,
		AgentRatio:              configPri.AgentRatio,
		RoomNotice:              "",
		ChatUrl:                 strings.Split(configPub.ChatUrl, ","),
		DlQrcode:                configPub.DlQrcode,
		DlWebUrl:                configPub.DlWebUrl,
		DlAndroid:               configPub.DlAndroid,
		DlAndroidPwa:            configPub.DlAndroidPwa,
		DlIos:                   configPub.DlIos,
		DlIosTf:                 configPub.DlIosTf,
		DlAndroidHw:             configPub.DlAndroidHw,
		DlIosHw:                 configPub.DlIosHw,
		VersionAndroid:          configPub.VersionAndroid,
		VersionIos:              configPub.VersionIos,
		Copyright:               configPub.Copyright,
		ServiceWxOfficial:       configPub.ServiceWxOfficial,
		ServiceWx:               configPub.ServiceWx,
		ServiceQq:               configPub.ServiceQq,
		ServiceURL:              configPub.ServiceURL,
		ServiceToggle:           configPub.ServiceToggle,
		SiteDomain:              configPub.SiteDomain,
		StreamUrl:               streams,
		BaseheatsStart:          configPub.BaseheatsStart,
		BaseheatsEnd:            configPub.BaseheatsEnd,
		SumbumistegurK:          configPub.SumbumistegurK,
		Populaarsuse:            configPub.Populaarsuse,
		GiftFactor:              configPub.GiftFactor,
		GiftTime:                configPub.GiftTime,
		ShareLiveUrl:            configPub.ShareLiveUrl,
		ImgDomain:               "",
		ImgUploadUrl:            configPub.ImgUploadUrl,
		License:                 configPub.License,
		ServiceEmail:            configPub.ServiceEmail,
		ApplyAnchor:             configPub.ApplyAnchor,
		ApkUpgradeToggle:        configPub.ApkUpgradeToggle,
		ApkUpgradeVersion:       configPub.ApkUpgradeVersion,
		ApkUpgradeURL:           configPub.ApkUpgradeURL,
		Wx_public:               configPub.WxPub,
		Weibo:                   configPub.Weibo,
		Douyin:                  configPub.Douyin,
		H5Domain:                configPub.H5Domain,
		ExpertAndroidToggle:     configPub.ExpertAndroidToggle,
		ExpertIosToggle:         configPub.ExpertIosToggle,
		GuessAndroidToggle:      configPub.GuessAndroidToggle,
		GuessIosToggle:          configPub.GuessIosToggle,
		AndroidMinVersion:       configPub.AndroidMinVersion,
		AndroidVersionNum:       configPub.AndroidVersionNum,
		ExpertPcToggle:          configPub.ExpertPcToggle,
		UpdateInfoIos:           configPub.UpdateInfoIos,
		UpdateInfoAndroid:       configPub.UpdateInfoAndroid,
		TalentListStatus:        configPub.TalentListStatus,
		AppiosUpgradeToggle:     configPub.AppiosUpgradeToggle,
		CaptchaPath:             configPub.CaptchaPath,
		CheckinSwitch:           configPub.CheckinSwitch,
		LotterySwitch:           configPub.LotterySwitch,
		VersionIosShop:          configPub.VersionIosShop,
		DlIosShopUrl:            configPub.DlIosShopUrl,
		UpdateInfoIosShop:       configPub.UpdateInfoIosShop,
		AppiosShopUpgradeToggle: configPub.AppiosShopUpgradeToggle,
		WorldcupThematicToggle:  configPub.WorldcupThematicToggle,
		WorldcupGuessToggle:     configPub.WorldcupGuessToggle,
		BusinessEmail:           configPub.BusinessEmail,
		FaceType:                configPub.FaceType,
		ForceUpdateOfficial:     configPub.ForceUpdateOfficial,
		PrivateChatWs:           configPub.PrivateChatWs,
		QuizFactor:              configPub.QuizFactor,
		VideoSwitch:             configPub.VideoSwitch,
		VideoPlayURL:            configPub.VideoPlayURL,
		ShareShortvideoUrl:      configPub.ShareShortvideoUrl,
		WatermarkToggle:         configPub.WatermarkToggle,
		WatermarkFile:           configPub.WatermarkFile,
		ServicePaopao:           configPub.ServicePaopao,
		Unkown:                  configPri.PullKey,
		AppFace:                 configPub.AppFace,
		SmsPromotion:            configPub.SmsPromotion,
		DialogTitle:             configPub.DialogTitle,
		DialogTimeout:           configPub.DialogTimeout,
		DialogForceReg:          configPub.DialogForceReg,
		DialogDailyTimes:        configPub.DialogDailyTimes,
		DialogWebImage:          configPub.DialogWebImage,
		DialogMobileImageH:      configPub.DialogMobileImageH,
		DialogMobileImageV:      configPub.DialogMobileImageV,
		DialogSwitch:            configPub.DialogSwitch,
		LivePreviewSwitch:       configPub.LivePreviewSwitch,
		ThirdUpload:             configPub.ThirdUpload,
		PrivateMessageToggle:    configPub.PrivateMessageToggle,
		ChatroomToggle:          configPub.ChatroomToggle,
		PopContact:              configPub.PopContact,
		EnableCaptcha:           configPub.EnableCaptcha,
		SlotMachineGame:         configPub.SlotMachineGame,
		LiveToggle:              configPub.LiveToggle,
		UserCenter:              configPub.UserCenter,
		SEMToNormalTimer:        configPub.SEMToNormalTimer,
		SEMToNormal:             configPub.SEMToNormal,
		SEMToNormal2:            configPub.SEMToNormal2,
		AppList:                 configPub.AppList,
		DLIOSUotxge:             configPub.DLIOSUotxge,
		DLIOSWebUotxge:          configPub.DLIOSWebUotxge,
		DLAndroidUotxge:         configPub.DLAndroidUotxge,
		MatchToggle:             configPub.MatchToggle,
		NewsToggle:              configPub.NewsToggle,
		AnonymousChatToggle:     configPub.AnonymousChatToggle,
		RechargeToggle:          configPub.RechargeToggle,
		TicketSwitch:            ticketSwitch,
	}

	if cache2.NewStatUserWatch().NeedOpenConfig(device, configPub.WatchDurToggle) {
		//老虎机游戏开关
		config.SlotMachineGame = 1
		//转盘抽奖开关
		config.LotterySwitch = 1
		//私聊开关
		config.PrivateMessageToggle = 1
		//直播开关
		config.LiveToggle = 1
		//直播聊天室
		config.ChatroomToggle = 1
		//我的用户中心开关
		config.UserCenter = 1
		//直播预告开关
		config.LivePreviewSwitch = 15 //1+2+4+8
	}

	chips := cache2.GetChips()

	// 推送使用统计
	err := global.PublisherStatistic.StatisticPush(
		publisher.UsageStatistic, base.GetAuthUserId(c), base.GetDeviceInfo(c), c.RealIP(), base.GetPlatform(c),
	)
	if err != nil {
		global.Log.Infof("stats error: %v", err)
	}

	return util.BuildSuccess(c, map[string]interface{}{"config": config, "chips": chips}, "")
}

// @Summary 升级配置信息
// @Description 升级配置信息
// @Accept  json
// @Produce  json
// @Tags Config
// @Success 200 {object} api_models.GetCommonConfigResp "result"
// @Router /api/upgrade/detail [POST]
func (base *Controller) UpgradeDetail(c echo.Context) error {
	configPub := cache2.GetConfigPub()

	streams := make([]map[string]interface{}, 0)
	_ = util.Json2Struct(configPub.StreamUrl, &streams)
	//if err != nil {
	//	return common.BuildFail(c, 1, "", err)
	//}
	config := &api_models.UpgradeConfigResp{
		ApkUpgradeToggle:  configPub.ApkUpgradeToggle,
		ApkUpgradeVersion: configPub.ApkUpgradeVersion,
		ApkUpgradeURL:     configPub.ApkUpgradeURL,
	}

	return util.BuildSuccess(c, map[string]interface{}{"config": config}, "")
}

func (base *Controller) GetTempKeysForCos(c echo.Context) error {
	// 获取临时密钥，计算签名
	tempKeys, err := tx.GetTempKeys()
	if err != nil {
		return util.BuildFail(c, 1, "", err)
	}
	return util.BuildSuccess(c, tempKeys, "")
}

func (base *Controller) GetSignForVod(c echo.Context) error {

	configPri := cache2.GetConfigPri()
	secretId := configPri.QcloudLiveSecretid
	secretKey := configPri.QcloudLiveSecretkey

	// 确定签名的当前时间和失效时间
	current := time.Now().Unix()
	expired := current + 86400 // 签名有效期：1天

	// 向参数列表填入参数
	// 计算签名
	randNum := string2.RandInt(0, 999999999)
	original := fmt.Sprintf("secretId=%s&currentTimeStamp=%d&expireTime=%d&random=%d",
		secretId, current, expired, randNum)
	hmac2 := encrypt.GenHMAC1([]byte(original), []byte(secretKey))
	hmac2 = append(hmac2, []byte(original)...)
	stringHmac := base64.StdEncoding.EncodeToString(hmac2)
	if len(stringHmac) <= 0 {
		return util.BuildFail(c, 1, "", nil)
	}
	return util.BuildSuccess(c, map[string]interface{}{"signature": stringHmac}, "")
}

// @Summary 取得中國地區
// @Description 取得中國地區
// @Accept  json
// @Produce  json
// @Tags Config
// @Success 200 {object} api_models.GetChinaCityResp "result"
// @Router /api/config/getChinaCity [POST]
func (base *Controller) GetChinaCity(c echo.Context) error {

	resp, err := base.Service.GetChinaCity()
	if err != nil {
		return util.BuildFail(c, 1, "", err)
	}
	return util.BuildSuccess(c, resp, "")
}

//// @Summary GetHomePopAd
//// @Description GetHomePopAd
//// @Accept  json
//// @Produce  json
//// @Tags Config
//// @Success 200 {object} models_main.Ads "result"
//// @Router /api/config/getHomePopAd [POST]
//func (base *Controller) ConfigGetHomePopAd(c echo.Context) error {
//	resp, err := base.Service.ConfigGetHomePopAd()
//	if err != nil {
//		return common.BuildFail(c, 1, "", err)
//	}
//	return common.BuildSuccess(c, resp, "")
//}

// @Summary GetAndroidPatch
// @Description GetAndroidPatch
// @Accept  json
// @Produce  json
// @Tags Config
// @Success 200 {object} []api_models.AndroidPatchResp "result"
// @Router /api/config/getAndroidPatch [POST]
func (base *Controller) GetAndroidPatch(c echo.Context) error {
	var (
		err  error
		req  = &api_models.AndroidPatchReq{}
		resp = make([]*api_models.AndroidPatchResp, 0)
	)

	if err = util.Json2Struct(c.Get("body").(string), req); err != nil {
		return util.BadParam(c, err)
	}
	if err = _const.Validate.Struct(req); err != nil || req.BaseCode < 1 {
		global.Log.Errorf("6GetAndroidPatch9参数错误%v", err)
		return util.BadParam(c, err)
	}
	if resp, err = base.Service.GetAndroidPatch(req.BaseCode); err != nil {
		return util.BuildFail(c, 1, "", err)
	}

	return util.BuildSuccess(c, resp, "")
}
